package com.beg.cant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beg.cant.entity.Comment;
import com.beg.cant.entity.User;
import com.beg.cant.mapper.CommentMapper;
import com.beg.cant.mapper.UserMapper;
import com.beg.cant.service.CommentService;
import com.beg.cant.vo.CommentsVO;
import com.beg.cant.vo.Replies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    public List<CommentsVO> getPostsByIdComment(Long id) {
        // 1. 查询所有评论并按 parentId 分组
        List<Comment> comments = commentMapper.selectList(
                new LambdaQueryWrapper<Comment>()
                        .eq(Comment::getPostId, id)
                        .orderByAsc(Comment::getCreatedAt)
        );
        if (CollectionUtils.isEmpty(comments)) {
            return Collections.emptyList(); // 提前返回空列表
        }
        // 2. 批量预加载用户信息（减少数据库查询）
        Set<Long> userIds = comments.stream()
                .map(Comment::getUserId)
                .collect(Collectors.toSet());
        Map<Long, User> userMap = userMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        // 3. 构建主评论Map（快速索引）
        Map<Long, CommentsVO> commentMap = new HashMap<>();
        List<CommentsVO> mainComments = new ArrayList<>();

        comments.forEach(comment -> {
            User user = userMap.get(comment.getUserId());
            CommentsVO vo = buildCommentVO(comment, user);

            if (comment.getParentId() == null) {
                mainComments.add(vo);
                commentMap.put(comment.getId(), vo);
            } else {
                CommentsVO parentVO = commentMap.get(comment.getParentId());
                if (parentVO != null) {
                    Replies reply = buildReply(comment, user, parentVO.getUserName());
                    parentVO.getReplies().add(reply); // 使用List存储回复
                }
            }
        });
        return mainComments;
    }

    private CommentsVO buildCommentVO(Comment comment, User user) {
        return CommentsVO.builder()
                .id(comment.getId())
                .avatar(user.getImage())
                .userName(user.getName())
                .content(comment.getContent())
                .date(comment.getCreatedAt())
                .replies(new ArrayList<>()) // 初始化空列表
                .build();
    }

    private Replies buildReply(Comment comment, User user, String replyTo) {
        return Replies.builder()
                .id(comment.getId())
                .avatar(user.getImage())
                .userName(user.getName())
                .replyTo(replyTo)
                .content(comment.getContent())
                .date(comment.getCreatedAt())
                .build();
    }
}
